package vcproj2cmake.reader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import jtools.files.TextFile;

import vcproj2cmake.Project;
import vcproj2cmake.Solution;

public class SolutionReader {

	
	public Solution readSolution(File file, File rootPath) throws IOException{
		
		if (!file.exists())
			return null;
		if (!file.canRead())
			return null;
		if (!file.getName().endsWith(".sln"))
			return null;

		TextFile tf = new TextFile();
		tf.readFile(file.getAbsolutePath(), false);
			
		ArrayList<String> projectFiles = new ArrayList<String>();
		ArrayList<String> projectNames = new ArrayList<String>();
		Solution solution = new Solution();
		solution.name = file.getName().replace(".sln", "");
		solution.file = file;
		solution.rootPath = rootPath;
		
		while(tf.hasNext()){
			String line = tf.getNextLine();
			if (line.contains(".vcproj")){
				String[] tmp = line.split(",");
				for (int i = 0; i < tmp.length; i++){
					if (tmp[i].contains(".vcproj")){
						projectFiles.add(tmp[i].replace("\"", "").trim());
						projectNames.add(tmp[i-1].split("=")[1].replace("\"", "").trim());
						System.out.println("Found Project: " + projectNames.get(projectNames.size()-1) + " : " + projectFiles.get(projectFiles.size()-1));
						System.out.println("ID: "+ tmp[i-1].split("=")[0].replace("Project(\"{", "").replace("}\") ", ""));
					}
				}
			}
		}
		tf.closeFile();
		File rootDir = file.getParentFile();
		for (int i = 0; i < projectFiles.size(); i++){
			VCPROJReader r = new VCPROJReader();
			File f = new File(rootDir + "/" + projectFiles.get(i));
			try {
				Project proj = r.readVcProjFile(f);
				if (proj != null)
					solution.projects.add(proj);
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch(Exception exp){
				exp.printStackTrace();
			}
		}
		
		solution.makePaths();
		solution.updateReferences();
		return solution;
	}
}
